package com.sample.write;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WriteActivity extends Activity implements OnClickListener{
    Button button1, button2;
    EditText text, text2;
    WebView wv;
    AlertDialog.Builder alert;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        wv=(WebView)findViewById(R.id.webView1);
        wv.loadUrl("www.google.com");
        button1=(Button)findViewById(R.id.button1);
        button1.setOnClickListener(this);
        button2=(Button)findViewById(R.id.button2);
        button2.setOnClickListener(this);
        text=(EditText)findViewById(R.id.editText1);
        text2=(EditText)findViewById(R.id.editText2);
        alert=new AlertDialog.Builder(this);
		alert.setTitle("Title");
		alert.setMessage("Are you sure?");
		alert.setPositiveButton("Ok", new android.content.DialogInterface.OnClickListener(){

		public void onClick(DialogInterface dialog, int which) {
			
		}});
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
	public void onClick(View v) {
		alert.show();
		if (v.getId() == button1.getId()){
        try{
        OutputStreamWriter out= new OutputStreamWriter(openFileOutput(text.getText().toString(), 0));
        out.write(text2.getText().toString());
        out.close();
        Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();	
        }
        catch(FileNotFoundException e){
        	Toast.makeText(this, "File Does Not Exist", Toast.LENGTH_LONG).show();	
        }
        catch(IOException e){
        	Toast.makeText(this, "Invalid Input", Toast.LENGTH_LONG).show();	
        }
		}
		if (v.getId() == button2.getId()){
		try{
		InputStream in=openFileInput(text.getText().toString());	
		if (in!= null){
		BufferedReader read=new BufferedReader(new InputStreamReader(in));
		String str;
		while((str=read.readLine())!=null){
			Toast.makeText(this, str, Toast.LENGTH_LONG).show();		
		}
		}
		in.close();
		}
        catch(FileNotFoundException e){
        	Toast.makeText(this, "File Does Not Exist", Toast.LENGTH_LONG).show();	
        }
        catch(IOException e){
        	Toast.makeText(this, "Invalid Input", Toast.LENGTH_LONG).show();	
        }
		}
	}
}